<template>
    <div class="container">
        <div class="header">
            <p>输入验证码</p>
        </div>

        <div class="info">
            <p>
                验证码已发送到
                <strong
                    class="phone-number"
                    :style="{ fontSize: 'larger' }"
                    ><span>{{ phoneNumber.slice(0, 3) }} {{ phoneNumber.slice(2, 7) }} {{ phoneNumber.slice(6) }}</span></strong
                >
                , 15分钟内填写有效
            </p>
        </div>
        <div class="captcha">
            <input
                v-for="(c, index) in ct"
                :key="index"
                type="number"
                v-model="ct[index]"
                ref="input"
                :style="{ borderBottomColor: index <= cIndex ? '#cd580f' : '' }"
                @input="
                    e => {
                        onInput(e.target.value, index);
                    }
                "
                @keydown.delete="
                    e => {
                        onKeydown(e.target.value, index);
                    }
                "
                @focus="onFocus"
                :disabled="loading" />
        </div>
        <!-- <p>{{ msg }}</p> -->
        <div class="resend">
            <van-button
                :disabled="!canResend"
                @click="handleResend">
                {{ resendButtonText }}
            </van-button>
        </div>
    </div>
</template>
<script>
import { Dialog } from 'vant';
import { Notify } from 'vant';
export default {
    data() {
        return {
            phoneNumber: '', // 假设通过路由参数传递过来
            ct: ['', '', '', ''],
            loading: false,
            msg: '验证提示',
            canResend: false, //倒计时是否开始
            resendCountdown: 60, //倒计时
            resendTimerId: null, //定时器,
        };
    },
    computed: {
        ctSize() {
            return this.ct.length;
        },
        cIndex() {
            let i = this.ct.findIndex(item => item === '');
            i = (i + this.ctSize) % this.ctSize;
            return i;
        },
        lastCode() {
            return this.ct[this.ctSize - 1];
        },
        resendButtonText() {
            return this.resendCountdown > 0 ? `重新发送 (${this.resendCountdown}s)` : '重新发送';
        },
        code() {
            return this.ct.join('');
        },
    },
    watch: {
        cIndex() {
            this.resetCaret();
        },
        lastCode(val) {
            if (val) {
                console.log('this.ctSize', this.ctSize);
                this.$refs.input[this.ctSize - 1].blur();
                this.sendCaptcha();
            }
        },
    },
    mounted() {
        // this.startResendCountdown();
        this.showKeyboard = true; // 保证页面加载时直接调起数字键盘
        this.resetCaret();
        this.phoneNumber = this.$route.params.phone;
        if (this.phoneNumber) {
            this.getCode(); //获取验证码
        }
    },
    beforeDestroy() {
        clearInterval(this.resendTimerId);
    },
    methods: {
        onInput(val, index) {
            val = val.replace(/\s/g, '');
            if (index == this.ctSize - 1) {
                this.ct[this.ctSize - 1] = val[0]; // 最后一个码，只允许输入一个字符。
            } else if (val.length > 1) {
                let i = index;
                for (i = index; i < this.ctSize && i - index < val.length; i++) {
                    this.ct[i] = val[i];
                }
                this.resetCaret();
            }
        },
        // 重置光标位置。
        resetCaret() {
            this.$refs.input[this.ctSize - 1].focus();
        },
        onFocus() {
            // 监听 focus 事件，将光标重定位到“第一个空白符的位置”。
            let index = this.ct.findIndex(item => item === '');
            index = (index + this.ctSize) % this.ctSize;
            console.log(this.$refs.input);
            this.$refs.input[index].focus();
        },
        onKeydown(val, index) {
            if (val === '') {
                // 删除上一个input里的值，并对其focus。
                if (index > 0) {
                    this.ct[index - 1] = '';
                    this.$refs.input[index - 1].focus();
                }
            }
        },
        sendCaptcha() {
            if (this.ct.join('') == '1234') {
                Dialog.alert({
                    title: '验证码错误',
                    message: '',
                    confirmButtonColor: '#1c70e4',
                }).then(() => {
                    this.loading = false;
                    this.$nextTick(() => {
                        this.reset();
                    });
                });
                return;
            }
            // this.msg = `发送验证码到服务器：${this.ct.join('')}`;
            // 此时无法操作 input。。
            this.loading = true;
            this.$http
                .post('/send/code', { code: this.ct.join(''), phoneNumber: this.phoneNumber })
                .then(res => {
                    const { success, data, msg } = res.data;
                    if (success) {
                    } else {
                        Dialog.alert({
                            title: '验证码错误',
                            message: '',
                            confirmButtonColor: '#1c70e4',
                        }).then(() => {
                            this.loading = false;
                            this.$nextTick(() => {
                                this.reset();
                            });
                            // setTimeout(() => {}, 3000);
                        });
                    }
                    Notify({ type: success ? 'success' : 'warning', message: msg });
                    success && this.$router.push('/my-interest');
                })
                .catch(err => {});
        },

        reset() {
            // 重置。一般是验证码错误时触发。
            this.ct = this.ct.map(item => '');
            this.resetCaret();
        },
        // 开始倒计时
        startResendCountdown() {
            this.resendCountdown = 60;
            this.canResend = false;
            this.resendTimerId = setInterval(() => {
                this.resendCountdown -= 1;
                this.canResend = this.resendCountdown === 0;
                if (this.canResend) clearInterval(this.resendTimerId);
                this.$forceUpdate(); // 强制更新以实时显示倒计时
            }, 1000);
        },
        handleResend() {
            if (!this.canResend) return;
            // 这里模拟重新发送验证码的逻辑，实际项目中请替换为实际的发送逻辑
            this.getCode();
        },
        // 获取验证码
        getCode() {
            this.$http
                .get('/get/code', { phooneNuber: this.phone })
                .then(res => {
                    const { success, data, msg } = res.data;
                    Notify({ type: success ? 'success' : 'warning', message: msg });
                    // 发送验证码成功，开始倒计时
                    if (success) {
                        this.startResendCountdown();
                    }
                })
                .catch(err => {});
        },
    },
};
</script>
<style lang="scss" scoped>
.container {
    text-align: left;
    .header {
        font-size: 2rem;
        margin-top: 4rem;
    }
    .info {
        color: gray;
        .phone-number {
            color: #020202;
        }
    }
    .resend {
        text-align: center;
    }
}
.captcha {
    display: flex;
    justify-content: center;
    margin-top: 40px;
}
input {
    margin-right: 20px;
    width: 45px;
    text-align: center;
    border: none;
    border-bottom: 1px solid #eee;
    font-size: 24px;
    outline: none;
    border-radius: 0;
}
input:last-of-type {
    margin-right: 0;
}
input:disabled {
    color: #000;
    background-color: #fff;
}
.msg {
    text-align: center;
}
.van-button--default {
    border: none;
}
</style>
